package com.xianyun.site.support.executor.filter.sms;

import com.xianyun.common.core.filter.Filter;
import com.xianyun.common.core.filter.FilterInvoker;
import com.xianyun.common.redis.service.RedisService;
import com.xianyun.site.support.common.constant.MessageConstants;
import com.xianyun.site.support.common.constant.SmsServiceConstants;
import com.xianyun.site.support.common.exception.SmsErrorCode;
import com.xianyun.site.support.common.exception.SmsException;
import com.xianyun.site.support.convertor.SmsConvertor;
import com.xianyun.site.support.domain.model.SmsMessage;
import com.xianyun.site.support.dto.SmsReceiveCmd;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author mac_zyj
 */
@Slf4j
@Component
public class SmsSendTooMuchFilter  implements Filter<SmsReceiveCmd> {

    private static final String SMS_ERROR_MESSAGE="短信发送过多，请过后再试!";

    @Autowired
    private RedisService redisService;

    @Override
    public void doFilter(SmsReceiveCmd context, FilterInvoker nextFilter) {
        SmsMessage message = SmsConvertor.toEntity(context.getSmsMessage());
        String redisKey = message.getRedisCheckKey(MessageConstants.TIMES_CHECK);
        Integer sendTimesInLastHour=redisService.getCacheObject(redisKey);
        if(null!=sendTimesInLastHour){
            if (sendTimesInLastHour>=SmsServiceConstants.CHECK_SMS_SEND_TIMES_TIMES_LIMITS) {
                SmsException smsException = new SmsException(SmsErrorCode.SMS_SEND_TOO_MUCH_ERROR, SMS_ERROR_MESSAGE);
                log.warn("SmsException with error code:{},error message:{}", smsException.getErrCode(), smsException.getMessage());
                throw smsException;
            }
        }
        nextFilter.invoke(context);
    }
}
